package com.itydl.imageloader;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.ImageView;

import com.itydl.imageloader.cache.ImageCache;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author ydl
 * @version 初学者代码
 */

public class ImageLoader {

    /**---------  缓存依赖抽象缓存接口ImageCache ---------**/
    private ImageCache mImageCache;

    //线程池，获取CPU核心数：Runtime.getRuntime().availableProcessors()
    private ExecutorService mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    //Handler
    private Handler mHandler = new Handler(Looper.getMainLooper());

    /**
     * 通过构造方法注入具体的缓存类型
     * @param imageCache
     */
    public ImageLoader(ImageCache imageCache) {
        this.mImageCache = imageCache;
    }

    /**
     * 展示图片
     */
    public void display(final String imageUrl, final ImageView imageView){
        Bitmap bitmap = mImageCache.get(imageUrl);
        //缓存中有图片，直接设置给ImageView
        if(bitmap != null){
            Log.e("ImageLoader","在缓存中获取图片");
            imageView.setImageBitmap(bitmap);
            return;
        }

        //走这里说明缓存中没有图片，请求网络下载
        //绑定url
        imageView.setTag(imageUrl);

        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = downLoadImageFromServer(imageUrl);
                if(bitmap == null){
                    //下载失败结束
                    Log.e("ImageLoader","下载失败");
                    return;
                }

                if(imageView.getTag().equals(imageUrl)){
                    //主线程更新
                    updataImageview(bitmap,imageView);
                }
                //把网络下载下来的图片缓存
                mImageCache.put(imageUrl,bitmap);
            }
        });
    }

    /**
     * 主线程更新UI
     * @param bitmap
     * @param imageView
     */
    private void updataImageview(final Bitmap bitmap, final ImageView imageView) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                imageView.setImageBitmap(bitmap);
            }
        });
    }


    /**
     * 从网络中下载图片
     * @param imageUrl
     */
    private Bitmap downLoadImageFromServer(String imageUrl) {
        Log.e("ImageLoader","网络获取图片");
        Bitmap bitmap = null;
        try {
            URL url= new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            bitmap = BitmapFactory.decodeStream(connection.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

}
